/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.dos;

import cn.easyplatform.lang.CaseInsensitiveHashMap;

import java.util.*;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class Record implements java.io.Serializable, Cloneable {

    /**
     *
     */
    private static final long serialVersionUID = -8588069260744552367L;

    private Map<String, FieldDo> map = new LinkedHashMap<String, FieldDo>();

    private List<String> key;

    /**
     * 设置值
     *
     * @param value 字段值
     * @return 记录本身
     */
    public Record set(FieldDo field) {
        map.put(field.getName(), field);
        return this;
    }

    /**
     * @param name
     * @return
     */
    public FieldDo get(String name) {
        if (null == name)
            return null;
        return map.get(name.toUpperCase());
    }

    /**
     * 返回记录中已有的字段的数量
     *
     * @return 记录中已有的字段的数量
     */
    public int getColumnCount() {
        return map.size();
    }

    /**
     * 返回记录中所有的字段名
     *
     * @return 记录中所有的字段名
     */
    public Set<String> getColumnNames() {
        return map.keySet();
    }

    /**
     * @return
     */
    public Collection<FieldDo> getData() {
        return map.values();
    }

    /**
     * @return
     */
    public List<String> getKey() {
        return key;
    }

    /**
     * @param key
     */
    public void setKey(List<String> key) {
        this.key = key;
    }

    @Override
    public Record clone() {
        Record record = new Record();
        if (map != null) {
            record.map = new LinkedHashMap<String, FieldDo>();
            for (Map.Entry<String, FieldDo> entry : map.entrySet())
                record.map.put(entry.getKey(), entry.getValue().clone());
        }
        if (key != null) {
            record.key = new ArrayList<String>();
            for (String k : key)
                record.key.add(k);
        }
        return record;
    }

    /**
     * 返回map格式的记录
     *
     * @return
     */
    public Map<String, Object> toMap() {
        Map<String, Object> data = new CaseInsensitiveHashMap();
        for (FieldDo f : map.values())
            data.put(f.getRawName(), f.getValue());
        return data;
    }
}
